<template>
	<!-- start:自定义页面内容 -->
	<div>
		<el-card class="box-card">
			<el-image :src="readingUrl"></el-image>
		</el-card>
	</div>
	<!-- end:自定义页面内容 -->
</template>

<script>
	import readingYnk from "@images/readcard/reading02.png";
	import {
		MessageBox
	} from "element-ui";
	import {
		WQReader
	} from "@api/tools/Hardware.js";

	export default {
		name: "Ynkdk",
		data() {
			return {
				ynkReader: new WQReader(),
				cardNo: "",
				timerhandle: {},
				readingUrl: this.loginUrl
			};
		},
		props: {
			loginUrl: String,
		},
		methods: {
			ReadedCard() {
				this.$emit("ReadedCard", this.cardNo);
			},
			async Readynk() {
				console.log("%c BeginReadeynk", "color:#01DFA5");
				if (this.destroyed) {
					return; // 防止页面关闭后 继续调用
				}
				///////////////////////////// 异步写法
				try {
					/** 读院内卡 */
					var cardno = await this.ynkReader.readCardId();
					if (cardno != "") {
						this.$emit("ReadedCard", cardno);
					} else {
						//设置定时器调用读卡器
						this.timerhandle = setTimeout(() => this.Readynk(), 500);
					}
				} catch (e) {
					console.log(`%c error: ${e.message}`, "color:red");
					MessageBox.alert(e.message, {
						confirmButtonText: "确定",
						callback: action => {
							setTimeout(() => {
								this.$router.push({
									name: "home"
								});
							}, 500);
						}
					});
				}
			},
			async Initynk() {
				if (this.destroyed) {
					return; // 防止页面关闭后 继续调用
				}
				try {
					var ret = await this.ynkReader.Init(0x00, "FFFFFFFFFFFF");
					if (ret) {
						this.Readynk();
					} else {
						this.ynkReader.Open()
						this.timerhandle = setTimeout(() => this.Initynk(), 1000);
					}
				} catch (e) {
					console.log(`%c error: ${e.message}`, "color:red");
					MessageBox.alert(e.message, {
						confirmButtonText: "确定",
						callback: action => {
							setTimeout(() => {
								this.$router.push({
									name: "home"
								});
							}, 500);
						}
					});
				}
			}
		},
		mounted() {
			this.ynkReader.Open()
				.then(() => this.Initynk())
				.catch(e => {
					MessageBox.alert(e.message, "读卡错误", {
						confirmButtonText: "确定",
						callback: action => {
							setTimeout(() => {
								this.$router.push({
									name: "home"
								});
							}, 500);
						}
					});
				});
		},
		beforeDestroy() {
			if (this.timerhandle != null) {
				clearTimeout(this.timerhandle);
				this.timerhandle = null;
			}
			this.destroyed = true;
			console.log("destroyed=" + this.destroyed);
		}
	};
</script>

<style scoped>
</style>
